package com.sjyl.kaoshitong.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.sjyl.kaoshitong.R;
import com.sjyl.kaoshitong.beans.ApiResponse;
import com.sjyl.kaoshitong.beans.QuestionItem;
import com.sjyl.kaoshitong.beans.Recontent;
import com.sjyl.kaoshitong.util.APIUtils;
import com.sjyl.kaoshitong.util.OKHttpUtil;
import com.sjyl.kaoshitong.util.PreferencesKeyUtil;
import com.sjyl.kaoshitong.util.ToastUtil;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by ChangerLow on 15/7/7.
 * Email: changerlow@qq.com
 */
public class QATwitterFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "QATwitterFragment";
    private LinearLayout refreshView;
    private LinearLayout commentsContainer;
    private LinearLayout emptyView;
    private LinearLayout errorView;
    private Button ansBtn;
    private Button starBtn;
    private ViewGroup mainContent;
    private OkHttpClient okHttpClient;
    private Gson gson = new Gson();




    public static QATwitterFragment newInstance(String id){
        QATwitterFragment fragment = new QATwitterFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id",id);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Hawk.init(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_qa_twitter_base_lyaout, container, false);
        refreshView = (LinearLayout)view.findViewById(R.id.refresh_layout);
        commentsContainer = (LinearLayout)view.findViewById(R.id.comment_container);
        emptyView = (LinearLayout)view.findViewById(R.id.emptyview);
        errorView = (LinearLayout)view.findViewById(R.id.error_view);
        mainContent = (NestedScrollView)view.findViewById(R.id.qa_twitter_content);
        okHttpClient = OKHttpUtil.getOkHttpClient(getActivity());

        ansBtn = (Button)view.findViewById(R.id.ansBtn);
        ansBtn.setOnClickListener(this);
        starBtn = (Button)view.findViewById(R.id.starBtn);
        starBtn.setOnClickListener(this);


        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showProgress();
        getQuestionData();
    }

    private void getQuestionData() {
        RequestBody body = new FormEncodingBuilder().add("funName", APIUtils.URL_FUNCTION_GET_QUE).add("departId", "1").add("userId", Hawk.get(PreferencesKeyUtil.KEY_USER_ID, "")).add("keyWord", Hawk.get(PreferencesKeyUtil.KEY_KEY_WORD, "")).build();
        //.add("catalogId", pid).add("funpage", String.valueOf(page)).build();
        Request request = new Request.Builder().url(APIUtils.BASE_URL).post(body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            Handler handler = new Handler(getActivity().getMainLooper());

            @Override
            public void onFailure(Request request, IOException e) {
                showErrorview();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String body = response.body().string();
                Logger.json(TAG, body);

                Type type = new TypeToken<ApiResponse<QuestionItem>>() {
                }.getType();
                final ApiResponse<QuestionItem> apiResponse = gson.fromJson(body, type);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!apiResponse.getRecode().equals("2000")) {
                            ToastUtil.SnackerShow(getActivity(), getActivity().getString(R.string.get_data_error));
                        } else {
                            Recontent<QuestionItem> recontent = apiResponse.getRecontent();

                            if (apiResponse.getRecontent() == null) {
                                showErrorview();
                                return;
                            }
                            List<QuestionItem> list = recontent.getRelist();
                            Logger.d(TAG, "=========recode:" + " relist size:" + list.size());
                            showContent();
                        }
                    }
                });
            }
        });
    }

    private void getCommentData(){

    }


    private void showProgress() {
        refreshView.setVisibility(View.VISIBLE);
        mainContent.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
    }

    private void showContent() {
        refreshView.setVisibility(View.GONE);
        mainContent.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);
    }

    private void showErrorview() {
        refreshView.setVisibility(View.GONE);
        mainContent.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);
    }

    private void showEmptyView(){
        refreshView.setVisibility(View.GONE);
        mainContent.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {

    }
}
